import {stringify} from 'querystring';
import {history} from 'umi';
import {fakeAccountLogin} from '@/services/login';
import {setAuthority} from '@/utils/authority';
import {getPageQuery} from '@/utils/utils';

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    // 第一个参数就是action
    // 第二个参数可以理解为上下文
    //  call api 这个api可以进行接口调用
    // put api 这个api用于触发reducer
    // 这两个api都需要加上yield的关键字
    * login({payload}, {call, put}) {
      const response = yield call(fakeAccountLogin, {
        username: payload.userName,
        password: payload.password,
        rememberMe: false
      });
      //{status: "ok", type: "account", currentAuthority: "admin"}
      //{status: "error", type: "account", currentAuthority: "guest"}
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully

      if (response.code === 0) {
        // 登录成功之后
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let {redirect} = params;

        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        history.replace(redirect || '/');
      }
    },

    logout() {
      const {redirect} = getPageQuery(); // Note: There may be security issues, please note

      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    // 第一个参数是state
    // 第二个参数是action
    changeLoginStatus(state, {payload}) {
      // 设置用户的角色
      setAuthority("admin");
      // 更新状态和账号类型 status: "ok", type: "account"
      return {...state, status: payload.code === 0 ? 'ok' : 'error', type: "account"};
    },
  },
};
export default Model;
